import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/pages/home/vip_service/mixin/vip_service_mixin.dart';
import 'package:tracker/pages/home/vip_service/model/vip_service_list_resp.dart';

import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';
import '../mixin/security_service_mixin.dart';

class SecurityRecord extends ConsumerStatefulWidget {
  const SecurityRecord({super.key});

  @override
  ConsumerState<SecurityRecord> createState() => _SecurityRecordState();
}

class _SecurityRecordState extends ConsumerState<SecurityRecord>
    with
        SecurityServiceMixin,
        VipServicePageMixin,
        AutomaticKeepAliveClientMixin {
  bool showLoading = true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getPackageList(1).then((value) {
        securityVipServiceData.clear();
        securityVipServiceData.addAll(value.data ?? []);
        showLoading = false;
        setState(() {});
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return showLoading
        ? Container(
            alignment: Alignment.center,
            child: CircularProgressIndicator(
              color: AppTheme.themeConfig.primaryColor,
            ),
          )
        : (securityVipServiceData.isNotEmpty ? buildBody() : const Center());
  }

  Widget buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 14, right: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
              padding: const EdgeInsets.only(left: 24, top: 20),
              child: lpText("套餐列表：")),
          Expanded(child: ListView.separated(
              padding: const EdgeInsets.only(top: 10),
              itemBuilder: (context, index) {
                if (index == securityVipServiceData.length) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Padding(
                          padding: const EdgeInsets.only(top: 24),
                          child: lpText("套餐内容:", size: 14)
                      ),
                      lpText(securityVipServiceData[securityIndex].content ?? "",  size: 14),

                    ],
                  );
                }
                return buildVip(index);
              },
              separatorBuilder: (context, index) {
                return const SizedBox(height: 10);
              },
              itemCount: securityVipServiceData.length + 1)),
          TextButton(
              onPressed: () {
                context.pushNamed('protocol', queryParameters: {'title': '会员服务协议', 'url': 'https://ljwl.tech/membership_agreement/index.html'});
              },
              child: const Text('《会员服务协议》',style: TextStyle(color: Colors.blue),)),
          Container(
            margin: const EdgeInsets.only(top: 16),
            alignment: Alignment.center,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                lpText("支付方式:"),
                const SizedBox(width: 10),
                buildContainer(
                    title: "支付宝",
                    image: "assets/images/pay/alipay_logo.png",
                    index: 0),
                const SizedBox(width: 10),
                buildContainer(
                    title: "微信",
                    image: "assets/images/pay/wxpay_logo.png",
                    index: 1)
              ],
            ),
          ),
          GestureDetector(
            onTap: payVip,
            child: Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              margin: const EdgeInsets.only(
                  left: 14, right: 14, top: 20, bottom: 30),
              padding: const EdgeInsets.symmetric(vertical: 8),
              decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor,
                  borderRadius: BorderRadius.circular(20)),
              child: lpText(
                  "确认并支付 ¥${securityVipServiceData[securityIndex].price}",
                  color: Colors.white,
                  size: 16),
            ),
          )
        ],
      ),
    );
  }

  void payVip() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (securityPayIndex == 0) {
      alipayUtils.createVip(
          securityVipServiceData[securityIndex].packageId?.toInt(),
          deviceInfo.imei.toString());
    } else {
      wxpayUtils.createVip(
          securityVipServiceData[securityIndex].packageId?.toInt(),
          deviceInfo.imei.toString(), securityVipServiceData[securityIndex].price?.toDouble());
    }
  }

  Widget buildContainer(
      {required String image, required String title, required int index}) {
    return GestureDetector(
      onTap: () {
        setState(() {
          securityPayIndex = index;
        });
      },
      child: Container(
        constraints: const BoxConstraints(minWidth: 100),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
                color: securityPayIndex == index
                    ? AppTheme.themeConfig.primaryColor
                    : AppTheme.themeConfig.secondaryTextColor.withOpacity(0.6),
                width: securityPayIndex == index ? 3 : 2)),
        child: Row(
          children: [
            Image.asset(image, width: 26, height: 26),
            const SizedBox(width: 6),
            lpText(title, size: 14)
          ],
        ),
      ),
    );
  }

  Widget buildVip(int index) {
    VipServiceData data = securityVipServiceData[index];
    bool isSelect = index == securityIndex;
    return GestureDetector(
      onTap: () {
        securityIndex = index;
        setState(() {});
      },
      child: AspectRatio(
          aspectRatio: 4.78,
          child: Stack(
            alignment: Alignment.centerRight,
            children: [
              Image.asset(isSelect
                  ? "assets/images/vip/icon_vip_border_bg.png"
                  : "assets/images/vip/icon_vip_grey_bg.png"),
              if (isSelect)
                Image.asset("assets/images/vip/icon_vip_blue_bg.png"),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  children: [
                    Expanded(
                        child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        lpText(data.title ?? "", size: 22),
                        lpText(data.subtitle ?? "")
                      ],
                    )),
                    RichText(
                        text: TextSpan(children: [
                      TextSpan(
                          text: "${data.price}",
                          style: TextStyle(
                              fontWeight: isSelect
                                  ? FontWeight.bold
                                  : FontWeight.normal,
                              fontSize: isSelect ? 35 : 26,
                              color: isSelect ? Colors.white : Colors.black)),
                      TextSpan(
                          text: " 元",
                          style: TextStyle(
                              color: isSelect ? Colors.white : Colors.black,
                              fontSize: isSelect ? 15 : 26)),
                    ]))
                  ],
                ),
              )
            ],
          )),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
